# -*- coding:utf-8 -*-

from fastapi import APIRouter, Depends, Request, Body, UploadFile, File
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List

from module_admin.aspect.interface_auth import CheckUserInterfaceAuth
from module_admin.annotation.log_annotation import Log
from module_admin.service.server_host_service import ServerHostService
from module_admin.service.login_service import LoginService
from module_admin.entity.vo.user_vo import CurrentUserModel
from module_admin.entity.vo.server_host_vo import (
    ServerHostModel,
    ServerHostQueryModel,
    ServerHostCreateModel,
    ServerHostUpdateModel,
    ServerHostBatchImportModel,
    CommandExecuteModel,
    AgentDeployModel,
    AgentControlModel,
    AgentLogQueryModel,
    BatchTestConnectionModel
)
from config.get_db import get_db
from config.enums import BusinessType
from utils.response_util import ResponseUtil
from utils.page_util import PageResponseModel
from utils.log_util import logger

serverHostController = APIRouter(prefix='/server/host', tags=['服务器主机管理'])


@serverHostController.get(
    '/list',
    response_model=PageResponseModel,
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:list'))]
)
async def get_host_list(
    request: Request,
    host_query: ServerHostQueryModel = Depends(ServerHostQueryModel),
    page_num: int = 1,
    page_size: int = 10,
    db: AsyncSession = Depends(get_db)
):
    """获取主机列表"""
    try:
        result = await ServerHostService.get_server_host_list(
            db, host_query, page_num, page_size
        )
        return ResponseUtil.success(model_content=result)
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.get(
    '/{host_id}',
    response_model=ServerHostModel,
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:query'))]
)
async def get_host_detail(
    request: Request,
    host_id: int,
    db: AsyncSession = Depends(get_db)
):
    """获取主机详情"""
    try:
        host = await ServerHostService.get_server_host_detail(db, host_id)
        if host:
            return ResponseUtil.success(model_content=host)
        return ResponseUtil.error(msg='主机不存在')
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.post(
    '/add',
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:add'))]
)
@Log(title='服务器主机管理', business_type=BusinessType.INSERT, log_type='operation')
async def add_host(
    request: Request,
    create_data: ServerHostCreateModel,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """添加主机"""
    try:
        await ServerHostService.create_server_host(
            db, create_data, current_user.user.user_id, current_user.user.dept_id
        )
        await db.commit()
        
        return ResponseUtil.success(msg='添加成功')
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.put(
    '/{host_id}',
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:edit'))]
)
@Log(title='服务器主机管理', business_type=BusinessType.UPDATE, log_type='operation')
async def update_host(
    request: Request,
    host_id: int,
    update_data: ServerHostUpdateModel,
    db: AsyncSession = Depends(get_db)
):
    """更新主机信息"""
    try:
        await ServerHostService.update_server_host(db, host_id, update_data)
        await db.commit()
        
        return ResponseUtil.success(msg='更新成功')
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.delete(
    '/batch',
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:remove'))]
)
@Log(title='服务器主机管理', business_type=BusinessType.DELETE, log_type='operation')
async def batch_delete_hosts(
    request: Request,
    host_ids: List[int] = Body(..., embed=True),
    db: AsyncSession = Depends(get_db)
):
    """批量删除主机"""
    try:
        await ServerHostService.batch_delete_server_hosts(db, host_ids)
        await db.commit()
        
        return ResponseUtil.success(msg='删除成功')
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.delete(
    '/{host_id}',
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:remove'))]
)
@Log(title='服务器主机管理', business_type=BusinessType.DELETE, log_type='operation')
async def delete_host(
    request: Request,
    host_id: int,
    db: AsyncSession = Depends(get_db)
):
    """删除主机"""
    try:
        await ServerHostService.delete_server_host(db, host_id)
        await db.commit()
        
        return ResponseUtil.success(msg='删除成功')
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.post(
    '/import',
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:import'))]
)
@Log(title='服务器主机管理', business_type=BusinessType.IMPORT, log_type='operation')
async def batch_import_hosts(
    request: Request,
    import_data: ServerHostBatchImportModel,
    auto_init_root: bool = False,
    test_connection: bool = True,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """批量导入主机"""
    try:
        result = await ServerHostService.batch_import_hosts(
            db, import_data, current_user.user.user_id, current_user.user.dept_id, auto_init_root, test_connection
        )
        await db.commit()
        
        msg = f'导入完成，成功{result["success_count"]}台，失败{result["failed_count"]}台'
        if auto_init_root and 'init_root_success' in result:
            msg += f'，root账号初始化成功{result["init_root_success"]}台'
        
        # 如果有失败的，提供更详细的提示
        if result["failed_count"] > 0:
            msg += f'\n\n失败原因：'
            for failed in result["failed_list"][:5]:  # 只显示前5个
                msg += f'\n• {failed["ip"]}: {failed["reason"]}'
            if result["failed_count"] > 5:
                msg += f'\n... 还有 {result["failed_count"] - 5} 台失败'
        
        return ResponseUtil.success(data=result, msg=msg)
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.post(
    '/test-connection/{host_id}',
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:test'))]
)
async def test_connection(
    request: Request,
    host_id: int,
    db: AsyncSession = Depends(get_db)
):
    """测试连接"""
    try:
        result = await ServerHostService.test_connection(db, host_id)
        await db.commit()
        
        if result['status'] == 'success':
            return ResponseUtil.success(data=result, msg='连接成功')
        else:
            return ResponseUtil.error(data=result, msg=result['message'])
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.post(
    '/batch-test-connection',
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:test'))]
)
@Log(title='批量测试连接', business_type=BusinessType.OTHER, log_type='operation')
async def batch_test_connection(
    request: Request,
    batch_test_model: BatchTestConnectionModel,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """批量测试连接"""
    try:
        results = await ServerHostService.batch_test_connection(db, batch_test_model.host_ids)
        await db.commit()
        
        success_count = sum(1 for r in results if r['status'] == 'success')
        failed_count = len(results) - success_count
        
        return ResponseUtil.success(
            data={'results': results},
            msg=f'测试完成，成功{success_count}台，失败{failed_count}台'
        )
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.post(
    '/init-root/{host_id}',
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:edit'))]
)
@Log(title='初始化root账号', business_type=BusinessType.UPDATE, log_type='operation')
async def init_root_account(
    request: Request,
    host_id: int,
    db: AsyncSession = Depends(get_db)
):
    """初始化root账号（将ubuntu等账号的密码设置给root，并切换到root登录）"""
    try:
        result = await ServerHostService.init_root_account(db, host_id)
        await db.commit()
        
        if result['status'] == 'success':
            return ResponseUtil.success(data=result, msg=result['message'])
        elif result['status'] == 'skipped':
            return ResponseUtil.success(data=result, msg=result['message'])
        else:
            return ResponseUtil.error(data=result, msg=result['message'])
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.post(
    '/batch-init-root',
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:edit'))]
)
@Log(title='批量初始化root账号', business_type=BusinessType.UPDATE, log_type='operation')
async def batch_init_root_account(
    request: Request,
    host_ids: List[int] = Body(...),
    db: AsyncSession = Depends(get_db)
):
    """批量初始化root账号"""
    try:
        results = await ServerHostService.batch_init_root_account(db, host_ids)
        await db.commit()
        
        success_count = sum(1 for r in results if r.get('status') == 'success')
        skipped_count = sum(1 for r in results if r.get('status') == 'skipped')
        failed_count = sum(1 for r in results if r.get('status') == 'failed')
        
        msg = f'批量初始化完成，成功{success_count}台，跳过{skipped_count}台，失败{failed_count}台'
        
        return ResponseUtil.success(
            data={'results': results},
            msg=msg
        )
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.post(
    '/execute-command',
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:command'))]
)
@Log(title='服务器命令执行', business_type=BusinessType.OTHER, log_type='operation')
async def execute_command(
    request: Request,
    execute_data: CommandExecuteModel,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """批量执行命令"""
    try:
        results = await ServerHostService.execute_command(
            db, execute_data, current_user.user.user_id
        )
        await db.commit()
        
        # 统计执行结果
        success_count = sum(1 for r in results if r.status == 'success')
        failed_count = len(results) - success_count
        
        return ResponseUtil.success(
            data={'results': [r.model_dump() for r in results]},
            msg=f'执行完成，成功{success_count}台，失败{failed_count}台'
        )
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.post(
    '/deploy-agent',
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:deploy'))]
)
@Log(title='Agent部署', business_type=BusinessType.OTHER, log_type='operation')
async def deploy_agent(
    request: Request,
    deploy_data: AgentDeployModel,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """批量部署Agent"""
    try:
        results = await ServerHostService.deploy_agent(
            db, deploy_data, current_user.user.user_id
        )
        await db.commit()
        
        # 统计执行结果
        success_count = sum(1 for r in results if r.status == 'success')
        failed_count = len(results) - success_count
        
        return ResponseUtil.success(
            data={'results': [r.model_dump() for r in results]},
            msg=f'部署完成，成功{success_count}台，失败{failed_count}台'
        )
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.post(
    '/control-agent',
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:control'))]
)
@Log(title='Agent控制', business_type=BusinessType.OTHER, log_type='operation')
async def control_agent(
    request: Request,
    control_data: AgentControlModel,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """批量控制Agent（启动/停止/重启）"""
    try:
        results = await ServerHostService.control_agent(
            db, control_data, current_user.user.user_id
        )
        await db.commit()
        
        # 统计执行结果
        success_count = sum(1 for r in results if r.status == 'success')
        failed_count = len(results) - success_count
        
        action_name = {'start': '启动', 'stop': '停止', 'restart': '重启'}.get(control_data.action, control_data.action)
        
        return ResponseUtil.success(
            data={'results': [r.model_dump() for r in results]},
            msg=f'{action_name}完成，成功{success_count}台，失败{failed_count}台'
        )
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.post(
    '/agent-log',
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:log'))]
)
async def get_agent_log(
    request: Request,
    query: AgentLogQueryModel,
    db: AsyncSession = Depends(get_db)
):
    """获取Agent日志"""
    try:
        result = await ServerHostService.get_agent_log(db, query)
        return ResponseUtil.success(data=result, msg='获取成功')
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.get(
    '/agent-log-dates/{host_id}',
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:log'))]
)
async def get_agent_log_dates(
    request: Request,
    host_id: int,
    db: AsyncSession = Depends(get_db)
):
    """获取可用的日志日期列表"""
    try:
        dates = await ServerHostService.get_agent_log_dates(db, host_id)
        return ResponseUtil.success(data={'dates': dates}, msg='获取成功')
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@serverHostController.get(
    '/check-agent-status/{host_id}',
    dependencies=[Depends(CheckUserInterfaceAuth('server:host:query'))]
)
async def check_agent_status(
    request: Request,
    host_id: int,
    db: AsyncSession = Depends(get_db)
):
    """检查Agent运行状态"""
    try:
        result = await ServerHostService.check_agent_status(db, host_id)
        await db.commit()
        
        return ResponseUtil.success(data=result, msg='检查成功')
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))

